from flask import Blueprint, request, jsonify
from applications.extensions import db
from applications.models import Role, Permission

# 创建 role 蓝图
role_bp = Blueprint('role', __name__, url_prefix='/system/role')

# --- 角色管理 (Role Management) ---

# 获取所有角色列表
@role_bp.route('/list', methods=['GET'])
def get_roles():
    """获取所有角色列表，支持查询和分页"""
    name = request.args.get('name')
    code = request.args.get('code')
    status = request.args.get('status')
    page = request.args.get('page', 1, type=int)
    limit = request.args.get('limit', 10, type=int)

    query = Role.query

    if name:
        query = query.filter(Role.name.like(f'%{name}%'))
    if code:
        query = query.filter(Role.code.like(f'%{code}%'))
    if status:
        query = query.filter(Role.status == status)

    pagination = query.paginate(page=page, per_page=limit, error_out=False)
    roles = pagination.items
    total = pagination.total

    role_list = []
    for role in roles:
        create_time_str = None
        if role.createTime:
            if hasattr(role.createTime, 'strftime'):
                create_time_str = role.createTime.strftime('%Y-%m-%d %H:%M:%S')
            else:
                create_time_str = role.createTime # 如果不是datetime对象，直接返回其值

        update_time_str = None
        if role.updateTime:
            if hasattr(role.updateTime, 'strftime'):
                update_time_str = role.updateTime.strftime('%Y-%m-%d %H:%M:%S')
            else:
                update_time_str = role.updateTime # 如果不是datetime对象，直接返回其值

        role_list.append({
            'id': role.id,
            'name': role.name,
            'code': role.code,
            'remark': role.remark,
            'status': role.status,
            'createTime': create_time_str,
            'updateTime': update_time_str
        })
    return jsonify({'code': 200, 'data': {'list': role_list, 'total': total, 'pageSize': limit, 'currentPage': page}})

# 创建新角色
@role_bp.route('/add', methods=['POST'])
def create_role():
    """创建新角色"""
    data = request.get_json()
    if not data or 'name' not in data or 'code' not in data:
        return jsonify({'code': 400, 'message': 'Role name and code are required'}), 400

    name = data.get('name')
    code = data.get('code')
    remark = data.get('remark')
    status = data.get('status', 1)

    if Role.query.filter_by(name=name).first():
        return jsonify({'code': 409, 'message': 'Role name already exists'}), 409
    if Role.query.filter_by(code=code).first():
        return jsonify({'code': 409, 'message': 'Role code already exists'}), 409

    new_role = Role(name=name, code=code, remark=remark, status=status)
    db.session.add(new_role)
    db.session.commit()
    return jsonify({'code': 201, 'message': 'Role created successfully', 'role_id': new_role.id})

# 更新指定角色信息
@role_bp.route('/update', methods=['POST'])
def update_role():
    """更新指定角色信息"""
    data = request.get_json()
    role_id = data.get('id')
    if not role_id:
        return jsonify({'code': 400, 'message': 'Role ID is required'}), 400
        
    role = Role.query.get(role_id)
    if not role:
        return jsonify({'code': 404, 'message': 'Role not found'}), 404

    role.name = data.get('name', role.name)
    role.code = data.get('code', role.code)
    role.remark = data.get('remark', role.remark)
    role.status = data.get('status', role.status)

    # 检查角色名和编码是否冲突
    if data.get('name') and data.get('name') != role.name and Role.query.filter(Role.id != role_id, Role.name == data.get('name')).first():
        return jsonify({'code': 409, 'message': 'Role name already exists'}), 409
    if data.get('code') and data.get('code') != role.code and Role.query.filter(Role.id != role_id, Role.code == data.get('code')).first():
        return jsonify({'code': 409, 'message': 'Role code already exists'}), 409

    db.session.commit()
    return jsonify({'code': 200, 'message': 'Role updated successfully'})

# 删除指定角色
@role_bp.route('/delete', methods=['POST'])
def delete_role():
    """删除指定角色"""
    role_id = request.json.get('id')
    if not role_id:
        return jsonify({'code': 400, 'message': 'Role ID is required'}), 400
        
    role = Role.query.get(role_id)
    if not role:
        return jsonify({'code': 404, 'message': 'Role not found'}), 404

    # 可以在这里添加逻辑，例如：如果该角色被任何用户使用，则不允许删除
    if role.admins:
        return jsonify({'code': 409, 'message': 'Cannot delete role that is assigned to users'}), 409

    db.session.delete(role)
    db.session.commit()
    return jsonify({'code': 200, 'message': 'Role deleted successfully'})


# 为角色分配权限
@role_bp.route('/assign_permissions', methods=['POST'])
def assign_permissions_to_role():
    """为角色分配权限"""
    data = request.get_json()
    role_id = data.get('role_id')
    if not role_id:
        return jsonify({'code': 400, 'message': 'Role ID is required'}), 400
        
    role = Role.query.get(role_id)
    if not role:
        return jsonify({'code': 404, 'message': 'Role not found'}), 404

    if 'permission_ids' not in data or not isinstance(data['permission_ids'], list):
        return jsonify({'code': 400, 'message': 'Invalid request body. Provide a list of permission_ids.'}), 400

    permission_ids = data['permission_ids']
    permissions_to_assign = Permission.query.filter(Permission.id.in_(permission_ids)).all()

    # 检查所有提供的 permission_ids 是否都存在
    if len(permissions_to_assign) != len(set(permission_ids)):
        return jsonify({'code': 404, 'message': 'One or more permissions not found'}), 404

    role.permissions = permissions_to_assign
    db.session.commit()
    return jsonify({'code': 200, 'message': f'Permissions assigned successfully to role {role_id}'})


# 获取角色当前拥有的权限
@role_bp.route('/permissions', methods=['GET'])
def get_role_permissions():
    """获取角色当前拥有的权限"""
    role_id = request.args.get('role_id')
    if not role_id:
        return jsonify({'code': 400, 'message': 'Role ID is required'}), 400
        
    role = Role.query.get(role_id)
    if not role:
        return jsonify({'code': 404, 'message': 'Role not found'}), 404

    role_permissions_data = []
    for perm in role.permissions:
        role_permissions_data.append({
            'id': perm.id,
            'name': perm.name,
            'code': perm.code,
            'description': perm.description,
            'endpoint': perm.endpoint
        })
    return jsonify({'code': 200, 'data': role_permissions_data})


# 注册管理端用户蓝图
def register_role_bps(app):
    app.register_blueprint(role_bp)
